package org.ezplatform.office.meeting.search.web.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.meeting.info.entity.ApplyRecord;
import org.ezplatform.office.meeting.notice.service.NoticeInfoService;
import org.ezplatform.office.meeting.search.service.SearchService;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName: SearchController
 * @Description: 会议查看控制类
 */
@RestController
@RequestMapping(value = "/api/w/searchController")
public class SearchWebApiController extends BaseController<ApplyRecord, String> {
	private final static Logger LOGGER = LoggerFactory.getLogger(SearchWebApiController.class);
	@Autowired
	private SearchService service;

    @Autowired
    private RestClient restClient;
    
    @Autowired
	private NoticeInfoService noticeInfoService;

    @Autowired
	private LogService logService;
    
    /*
	 * (非 JAVADOC) <p>Title: getEntityService</p> <p>Description: </p>
	 * 
	 * @return
	 * 
	 */
	@Override
	protected BaseService<ApplyRecord, String> getEntityService() {
		return service;
	}

	/**
	 * 
	 * @Title: prepareModel
	 * @Description: 初始化数据
	 * @param request
	 * @param model
	 * @param id
	 * @return void
	 * @throws
	 */
	@ModelAttribute
	public void prepareModel(HttpServletRequest request, Model model,
			@RequestParam(value = "id", required = false) String id) {
		super.initPrepareModel(request, model, id);
	}
	
	/**
     * 
     * @Title: createOwnList
     * @Description: 我发起的会议和我参与的会议合并（翻页）
     * @param request
     * @return
     * @return PageOaMeetingBaseSet
     * @throws
     */
    @RequestMapping(value = "/ownList", method = RequestMethod.GET)
    public Page ownList(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String roleCodes = StringUtils.null2String(user.getRoleCodes());
        int isAdminRole = 0;
        if(roleCodes.contains("appAdminRole")) isAdminRole = 1;
        Pageable localPageable = PropertyFilter.buildPageableFromHttpRequest(request);
        //名称
        String name = ValidateUtils.filter(request.getParameter("createName"));
        //名称
        String status = ValidateUtils.filter(request.getParameter("createStatus"));
        return this.service.getSearchList(localPageable,corpId,name,status,666,isAdminRole,TOKEN);
    }
	
    /**
     * 查询单个周期内的会议
     * @param request
     * @return
     */
    @RequestMapping(value = "/cycleMeetingForm", method = RequestMethod.GET)
    public Page cycleMeetingForm(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String userId = StringUtils.null2String(user.getUserId());
        String corpId = StringUtils.null2String(user.getCorpId());
        String token = StringUtils.null2String(user.getJwtToken());
        String roleCodes = StringUtils.null2String(user.getRoleCodes());
        int isAdminRole = 0;
        if(roleCodes.contains("appAdminRole")) isAdminRole = 1;
        Pageable localPageable = PropertyFilter.buildPageableFromHttpRequest(request);
        String cycleId = ValidateUtils.filter(request.getParameter("cycleId"));
        String startTime = ValidateUtils.filter(request.getParameter("startTime"));
        String endTime = ValidateUtils.filter(request.getParameter("endTime"));
        String status = ValidateUtils.filter(request.getParameter("createStatus"));
        String type = request.getParameter("type");
        return this.service.getCycleMeetingForm(localPageable, cycleId, corpId, startTime, endTime, status, userId, isAdminRole, token, type);
    }
    
    /**
     * 查询周期会议
     * @param request
     * @return
     */
    @RequestMapping(value = "/cycleMeetingList", method = RequestMethod.GET)
    @RequiresPermissions({"meeting:meeting:03"})
    public Page getCycleMeetingList(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String userId = StringUtils.null2String(user.getUserId());
        String corpId = StringUtils.null2String(user.getCorpId());
        String roleCodes = StringUtils.null2String(user.getRoleCodes());
        int isAdminRole = 0;
        if(roleCodes.contains("appAdminRole")) isAdminRole = 1;
        Pageable localPageable = PropertyFilter.buildPageableFromHttpRequest(request);
        String type = ValidateUtils.filter(request.getParameter("type"));
        String name = ValidateUtils.filter(request.getParameter("createName"));
        String cycleType = ValidateUtils.filter(request.getParameter("cycleType"));
        return this.service.getCycleMeeting(localPageable, type, corpId, name, cycleType, userId, isAdminRole, TOKEN,user);
    }
    
	/**
     * 
     * @Title: createOwnList
     * @Description: 获取我发起的列表数据（翻页）
     * @param request
     * @return
     * @return PageOaMeetingBaseSet
     * @throws
     */
    @RequestMapping(value = "/createOwnList", method = RequestMethod.GET)
    public Page createOwnList(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String roleCodes = StringUtils.null2String(user.getRoleCodes());
        int isAdminRole = 0;
        if(roleCodes.contains("appAdminRole")) isAdminRole = 1;
        Pageable localPageable = PropertyFilter.buildPageableFromHttpRequest(request);
        //名称
        String name = ValidateUtils.filter(request.getParameter("createName"));
        //名称
        String status = ValidateUtils.filter(request.getParameter("createStatus"));
        return this.service.getSearchList(localPageable,corpId,name,status,0,isAdminRole,TOKEN);
    }
    
    /**
     * 
     * @Title: attendOwnList
     * @Description: 获取我参与列表数据（翻页）
     * @param request
     * @return
     * @return PageOaMeetingBaseSet
     * @throws
     */
    @RequestMapping(value = "/attendOwnList", method = RequestMethod.GET)
    public Page attendOwnList(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String roleCodes = StringUtils.null2String(user.getRoleCodes());
        int isAdminRole = 0;
        if(roleCodes.contains("appAdminRole")) isAdminRole = 1;
        Pageable localPageable = PropertyFilter.buildPageableFromHttpRequest(request);
        //名称
        String name = ValidateUtils.filter(request.getParameter("attendName"));
        //名称
        String status = ValidateUtils.filter(request.getParameter("attendStatus"));
        return this.service.getSearchList(localPageable,corpId,name,status,1,isAdminRole,TOKEN);
    }
    
    /**
     * 
     * @Title: searchAllList
     * @Description: 获取所有列表数据（翻页）
     * @param request
     * @return
     * @return PageOaMeetingBaseSet
     * @throws
     */
    @RequestMapping(value = "/searchAllList", method = RequestMethod.GET)
    @RequiresPermissions({"meeting:meeting:03"})
    public Page searchAllList(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String roleCodes = StringUtils.null2String(user.getRoleCodes());
        int isAdminRole = 0;
        if(roleCodes.contains("appAdminRole")) isAdminRole = 1;
        Pageable localPageable = PropertyFilter.buildPageableFromHttpRequest(request);
        //名称
        String name = ValidateUtils.filter(request.getParameter("name"));
        //名称
        String status = ValidateUtils.filter(request.getParameter("status"));
        return this.service.getSearchList(localPageable,corpId,name,status,3,isAdminRole,TOKEN);
    }

    /**
     * 查询预定会议
     * @param request
     * @return
     */
    @RequestMapping(value = "/searchApplyList", method = RequestMethod.GET)
    @RequiresPermissions({"meeting:reserve:03"})
    public Page searchApplyList(HttpServletRequest request) {
    	LOGGER.info("----searchApplyList----");
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();

        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("userId", user.getUserId());
        paramMap.put("corpId", corpId);
        paramMap.put("module", "meeting");
        paramMap.put("type", "1,2");
        paramMap.put("category", "meetingProgress");
        // 流程管理员
        List<String> managerList = new ArrayList<String>();
        // 流程可查看人
        List<String> readList = new ArrayList<String>();
        long time=System.currentTimeMillis();
        try {
            // 查询当前用户具有查看流程的权限以及是否是流程管理员
            String principalName = restClient.post("/bpm/process/getProcessCodeByUserId", user.getJwtToken(), paramMap);
            LOGGER.debug("------zhaozy1:"+(System.currentTimeMillis()-time));
            time=System.currentTimeMillis();
            LOGGER.info("--principalName:"+principalName);
            Map<String,Object> map = JsonUtils.readValue(principalName);
            LOGGER.debug("------zhaozy2:"+(System.currentTimeMillis()-time));
            time=System.currentTimeMillis();
            if(map.get("type").toString().equals("success")){
                // 返回结果
                Map<String, Object> dataMap = (Map<String, Object>) map.get("data");

                // 流程管理员的code
                managerList = (List<String>) dataMap.get("keeperList");
                // 流程可查看人的code
                readList = (List<String>) dataMap.get("viewList");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
        // 查询列表数据
        String boardroomName = ValidateUtils.filter(request.getParameter("boardroomName"));
        String bpmStatus = ValidateUtils.filter(request.getParameter("bpmStatus"));
        String startTime = ValidateUtils.filter(request.getParameter("startTime"));
        String endTime = ValidateUtils.filter(request.getParameter("endTime"));
        LOGGER.debug("------zhaozy3:"+(System.currentTimeMillis()-time));
        time=System.currentTimeMillis();
        Page<Map> page = this.service.getSearchApplyList(pageable, corpId, boardroomName, startTime, endTime, bpmStatus, readList);
        LOGGER.debug("------zhaozy4:"+(System.currentTimeMillis()-time));
        time=System.currentTimeMillis();
        List<Map> content = page.getContent();
        for(int i=0; i<content.size(); i++){
            Map<String, Object> map = content.get(i);
            String procDefId = StringUtils.null2String(map.get("procDefId"));
            map.put("processKey", "");
            if(procDefId != ""){
                String code = procDefId.substring(0,procDefId.indexOf(":"));
                if(managerList.contains(code)){
                    map.put("canEdit", "1");
                }else{
                    map.put("canEdit", "0");
                }
                map.put("processKey", code);
            }
        }
        return page;
    }
    
    /**
     * 删除（批量）数据
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public OperationResult delete(@RequestParam("ids") String... ids) {
        return super.delete(ids);
    }

    /**
     * 删除功能
     * @return
     */
    @RequestMapping(value = "/deleteBpm", method = RequestMethod.POST)
    public OperationResult deleteBpm(HttpServletRequest request, @RequestParam("ids") String... ids) {
    	Map failureMap = new HashMap();
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String userId = user.getUserId();
        String token = user.getJwtToken();
        Map<String,String> paramMap = new HashMap<String,String>();
        paramMap.put("corpId", corpId);
        paramMap.put("userId", userId);

        try {
            if (null != ids && ids.length > 0) {
                List<String> dataIdList = new ArrayList<>();
                Map<String,String> paramMap2 = new HashMap<String,String>();
                boolean canLog = logService.checkOptLog(corpId, "meeting:query:04", token);
                //批量记录日志
                List<Map<String, String>> operateDataList = new ArrayList<>();
                for (int i = 0; i < ids.length; i++) {
                    String id = ids[i];
                    if(StringUtils.isNotBlank(id)){
                        String[] idArray = id.split("\\|");
                        String processInstanceId = idArray[1];
                        String dataId = idArray[0];
                        paramMap.put("processInstanceId", processInstanceId);
                        //删除流程消息
                        String taskId = getAllTaskIds(userId, corpId, processInstanceId, token);
                        String title = service.getTitleByProInsId(processInstanceId);
                        deleteMessages(userId, corpId, taskId, token, "meeting");
                        paramMap2.put("processInstanceIds", processInstanceId);
                        //释放自动编号
                        restClient.post("/bpm/process/releaseProcessForm", token, paramMap2);
    					//删除流程数据
                        String result = restClient.post("/bpm/runtime/deleteProcessInstance", token, paramMap);
                        Map<String,Object> map = JsonUtils.readValue(result);
                        if(map.get("type").toString().equals("success")){
                            dataIdList.add(dataId);
                            if(canLog) {
                            	Map<String, String> operateDataMap = new HashMap<>();
                				// 操作数据
                				operateDataMap.put("operateData", title);
                				// 操作明细
                				operateDataMap.put("operateDetails", "");
                				// 请求Id
                				operateDataMap.put("requestId", null);
                				operateDataList.add(operateDataMap);
                            }
                        }
                    }
                }
    			// 记录批量日志
                if(canLog) logService.batchSaveModuleLog("meeting:query:04", operateDataList, request);
                // 删除数据
                if (dataIdList != null && dataIdList.size() > 0) {
                    int no = this.service.deleteApplyRecord(dataIdList);
                    if (no >= 0) {
                    	failureMap.put("i18NCode", "oa.meeting.delsuccess");
                        return OperationResult.buildSuccessResult("删除成功",failureMap);
                    } else {
                    	failureMap.put("i18NCode", "oa.meeting.delfalse");
                        return OperationResult.buildFailureResult("删除失败",failureMap);
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            failureMap.put("i18NCode", "oa.meeting.delfalse");
            return OperationResult.buildFailureResult("删除失败",failureMap);
        }
        failureMap.put("i18NCode", "oa.meeting.delsuccess");
        return OperationResult.buildSuccessResult("删除成功",failureMap);
    }
    
    public String getAllTaskIds(String userId, String corpId, String processInstanceId, String token){
        Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("corpId", corpId);
            paramMap.put("userId", userId);
            paramMap.put("processInstanceId", processInstanceId);
            String scopeMap = restClient.get("/bpm/runtime/getProcessInfo", token, paramMap);
            Map<String, Object> map = JsonUtils.readValue(scopeMap);
            String taskIds="";
            if (map.get("type").toString().equals("success")) {
                Map<String, Object> resultMap = (Map<String, Object>) map.get("data");
                List<Map<String, Object>> doneUserList = (List<Map<String, Object>>) resultMap.get("doneUserList");
                if (null!=doneUserList && doneUserList.size() > 0) {
                    for (int d = 0; d < doneUserList.size(); d++) {
                      String taskId=doneUserList.get(d).get("taskId").toString();
                      taskIds+=","+taskId;
                    }
                }
                List<Map<String, Object>> doingUserList = (List<Map<String, Object>>) resultMap.get("doingUserList");
                if (null!=doingUserList && doingUserList.size() > 0) {
                    for (int d = 0; d < doingUserList.size(); d++) {
                      String taskId=doingUserList.get(d).get("taskId").toString();
                      taskIds+=","+taskId;
                    }
                }
                if(StringUtils.isNotBlank(taskIds)){
                   return  taskIds.substring(1);
                }
            }
        return taskIds;
      }
    
    public String deleteMessages(String userId,String corpId,String taskId,String token,String module){
        String taskIds[]=taskId.split(",");
        Map<String, String> endMap=new HashMap<String, String>();
        endMap.put("moduleCode", module);
        endMap.put("corpId", corpId);
        for (int i = 0; i < taskIds.length; i++) {
           endMap.put("dataId", taskIds[i]);
           restClient.post("/system/umc/message/deleteMessages", token, endMap);
        }
        if(!"urge".equals(module)){
            deleteMessages(userId, corpId, taskId, token, "urge");
        }
        return OperationResult.SUCCESS;
    }
    
    /**
     * 变更记录人
     * @param request
     * @return
     */
    @RequestMapping(value = "/changMemoUser", method = RequestMethod.POST)
    public OperationResult changMemoUser(HttpServletRequest request) {
    	Map failureMap = new HashMap();
    	try {
    		String applyRecordId = ValidateUtils.filter(request.getParameter("applyRecordId"));
    		String memoUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrMemoUser"));
    		if(StringUtils.isNotBlank(memoUserJsonStr)) {
				Map<String, String> map = noticeInfoService.getUserIdAndName(memoUserJsonStr);
				String newMemoUserId = map.get("id");
				String newMemoUserName = map.get("name");
				service.changMemoUser(applyRecordId, newMemoUserId, newMemoUserName);
    		}
        }catch (Exception e) {
            e.printStackTrace();
            failureMap.put("i18NCode", "oa.meeting.savefalse");
            return OperationResult.buildFailureResult("保存失败",failureMap);
        }
    	failureMap.put("i18NCode", "oa.meeting.savesuccess");
        return OperationResult.buildSuccessResult("保存成功",failureMap);
    }
}
